<template>
  <div class="articles-container">
    <div class="page-header">
      <h2>文章管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增文章
      </el-button>
    </div>

    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="文章标题">
          <el-input 
            v-model="filterForm.title" 
            placeholder="请输入文章标题" 
            clearable
            @keyup.enter="handleFilter"
          />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="全部状态" clearable style="width: 100px">
            <el-option label="草稿" value="draft" />
            <el-option label="审核中" value="pending" />
            <el-option label="已发布" value="published" />
          </el-select>
        </el-form-item>

        <el-form-item label="分类">
          <el-select
            v-model="filterForm.categories"
            placeholder="选择分类"
            clearable
            multiple
            collapse-categories
            collapse-categories-tooltip
            style="width: 165px"
          >
            <el-option
              v-for="category in categoryOptions"
              :key="category"
              :label="category"
              :value="category"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="articles"
        style="width: 100%"
        border
      >
        <el-table-column type="expand">
          <template #default="props">
            <div class="article-detail">
              <div class="content">
                <div v-html="props.row.content"></div>
              </div>
              <div class="stats">
                <div class="stat-item">
                  <el-icon><Star /></el-icon>
                  <span>收藏: {{ props.row.favoriteCount || 0 }}</span>
                </div>
                <div class="stat-item">
                  <el-icon><Pointer /></el-icon>
                  <span>点赞: {{ props.row.likeCount || 0 }}</span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="authorId" label="作者" width="120">
          <template #default="{ row }">
            <el-tooltip 
              :content="row.author?.username || '未知作者'" 
              placement="top"
            >
              <span>{{ row.author?.username || row.authorId }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="分类" width="200">
          <template #default="{ row }">
            <el-tag
              v-for="category in row.categories"
              :key="category"
              size="small"
              class="mr-1"
            >
              {{ category }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
            <el-dropdown trigger="click" @command="(command) => handleCommand(command, row)">
              <el-button link size="small" style="margin-top: 5px;margin-left: 10px;">
                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item 
                    v-for="action in getAvailableActions(row.status)" 
                    :key="action.command" 
                    :command="action.command"
                  >
                    {{ action.label }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 文章编辑对话框 -->
    <ArticleDialog
      v-model="dialogVisible"
      :article="currentArticle"
      @success="handleSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, View, Star, Pointer, ArrowDown } from '@element-plus/icons-vue'
import { 
  getArticles, 
  deleteArticle, 
  updateArticleStatus
} from '@/views/api/article'
import ArticleDialog from './components/ArticleDialog.vue'

// 状态和数据
const loading = ref(false)
const articles = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)
const currentArticle = ref(null)

// 过滤表单
const filterForm = reactive({
  title: '',
  status: '',
  categories: []
})

// 分类选项（实际项目中可能需要从后端获取）
const categoryOptions = ref([
  '旅游攻略',
  '景点介绍',
  '美食推荐',
  '住宿指南',
  '交通指南',
  '购物指南'
])

// 获取文章列表
const fetchArticles = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      search: filterForm.title,
      status: filterForm.status,
      categories: filterForm.categories
    }
    const response = await getArticles(params)
    if (response.data && response.data.data) {
      articles.value = response.data.data.items
      total.value = response.data.data.total
    }
  } catch (error) {
    ElMessage.error('获取文章列表失败')
    console.error('Error fetching articles:', error)
  } finally {
    loading.value = false
  }
}

// 状态处理函数
const getStatusType = (status) => {
  const types = {
    draft: 'info',
    pending: 'warning',
    published: 'success'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    draft: '草稿',
    pending: '审核中',
    published: '已发布'
  }
  return texts[status] || status
}

// 获取可用操作
const getAvailableActions = (status) => {
  const actions = {
    draft: [
      { command: 'publish', label: '发布' },
      { command: 'pending', label: '提交审核' }
    ],
    pending: [
      { command: 'publish', label: '发布' },
      { command: 'draft', label: '退回草稿' }
    ],
    published: [
      { command: 'draft', label: '退回草稿' },
      { command: 'pending', label: '重新审核' }
    ]
  }
  return actions[status] || []
}

// 日期格式化
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 过滤和重置
const handleFilter = () => {
  currentPage.value = 1
  fetchArticles()
}

const resetFilter = () => {
  filterForm.title = ''
  filterForm.status = ''
  filterForm.categories = []
  handleFilter()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchArticles()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchArticles()
}

// 文章操作
const handleAdd = () => {
  currentArticle.value = null
  dialogVisible.value = true
}

const handleEdit = (row) => {
  currentArticle.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这篇文章吗？此操作不可恢复', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteArticle(row.articleId)
    ElMessage.success('删除成功')
    fetchArticles()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('Error deleting article:', error)
    }
  }
}

const handleCommand = async (command, row) => {
  try {
    // 状态映射
    const statusMap = {
      'publish': 'published',
      'pending': 'pending',
      'draft': 'draft'
    }
    
    const newStatus = statusMap[command]
    if (!newStatus) {
      ElMessage.error('无效的操作')
      return
    }
    
    await updateArticleStatus(row.articleId, newStatus)
    ElMessage.success('状态更新成功')
    fetchArticles()
  } catch (error) {
    ElMessage.error('状态更新失败')
    console.error('Error updating article status:', error)
  }
}

const handleSuccess = () => {
  dialogVisible.value = false
  fetchArticles()
}

// 初始化
onMounted(() => {
  fetchArticles()
})
</script>

<style scoped>
.articles-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-weight: 600;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-form .el-form-item {
  margin-bottom: 0;
  margin-right: 16px;
}

.table-card {
  margin-bottom: 20px;
}

.article-detail {
  padding: 20px;
  
  .stats {
    display: flex;
    gap: 20px;
    margin-top: 10px;
    
    .stat-item {
      display: flex;
      align-items: center;
      gap: 5px;
      color: #666;
      
      .el-icon {
        font-size: 16px;
      }
    }
  }
}

.content {
  margin-bottom: 20px;
}

.content :deep(*) {
  max-width: 100%;
  overflow-wrap: break-word;
}

.content :deep(img) {
  max-width: 100%;
  height: auto;
}

.content :deep(p) {
  margin: 10px 0;
  color: #666;
}

.content :deep(h1),
.content :deep(h2),
.content :deep(h3),
.content :deep(h4),
.content :deep(h5),
.content :deep(h6) {
  margin: 16px 0 8px 0;
  font-weight: 600;
}

.content :deep(ul),
.content :deep(ol) {
  padding-left: 20px;
  margin: 10px 0;
}

.content :deep(li) {
  margin: 5px 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.mr-1 {
  margin-right: 5px;
}
</style>